package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yangeit
 * @date 2023年11月22日 14:58
 * @Description
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;
    @Override
    public User login(UserLoginDTO userLoginDTO) {

//        1.通过授权码获得openid
         String openId = getOpenId(userLoginDTO.getCode());

//        2.判断openid是否存在
        if (StringUtils.isEmpty(openId)){
            throw new LoginFailedException("登录失败，请重新再试！");
        }

//        3.通过Openid查询user表，获取user信息
      User user=  userMapper.getUserByOpenId(openId);

//        4. 判断user是否存在
        if (user==null){
//            5.新建用户
             user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());

            userMapper.insert(user);

        }


        return user;
    }


    /**
     * 通过授权码获取OpenId
     * @param code
     * @return
     */
    public String getOpenId(String code){
//路径:
        Map<String, String> map = new HashMap<>();
//        todo 将appid放到yml文件
//        小程序appid
        map.put("appid","wx32773db69ea85746");
//        秘钥
        map.put("secret","7c8d3a5dc80c95d5926b6699d4f3bf3e");
//        授权码
        map.put("js_code",code);
//        授权类型
        map.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", map);

         JSONObject parse = JSON.parseObject(json);
         String openid = parse.getString("openid");

         return openid;

    }

}
